package io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import structure.Move;
import structure.SympleBoard;
import utils.Param;

import ai.AI;
import ai.evaluation.DummyEvaluator;

public class MessageManager {
	
	private static AI ai = null;
	
	public static void start() throws IOException{
		Logger.init();
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while((line=reader.readLine())!=null){
			digestMessage(line);
		}
	}
	
	public static void sendMessage(String message){
		System.out.println(message);
		System.out.flush();
	}
	
	private static void digestMessage(String message){
		if(message.equals("Quit")){
			System.exit(0);
		} else if(message.equals("Start")){
			init((byte)-1);
		} else {
			if(ai == null)
				init((byte)1);
			ai.play(new Move(message, (byte)(ai.getColor()*-1)));
		}
		
		//aiPlay();
		
		Logger.logln(ai.getBoard().getClass(), ai.getBoard().toString());
	}
	
	private static void aiPlay(){
		Move move = ai.getMove(ai.getBoard(), ai.getColor());
		ai.play(move);
		sendMessage(move.toString());
	}
	
	private static void init(byte color){
		try {
			ai = AI.create(Param.AI, new DummyEvaluator(), color, new SympleBoard(Param.SIZE));
			Logger.logln(ai.getClass(), ai.toString());
		} catch (InstantiationException e) {
			Logger.logln(MessageManager.class, e.toString());
		} catch (IllegalAccessException e) {
			Logger.logln(MessageManager.class, e.toString());
		} catch (ClassNotFoundException e) {
			Logger.logln(MessageManager.class, e.toString());
		}
	}
}
